import type { DeptEntityReq } from "@/api/types";
import type { UseBaseForm } from "@/composables";
import { ElMessage } from "element-plus";
import { deptApi } from "@/api";
import { useBaseForm } from "@/composables";
import { $t } from "@/plugins/i18n";
import { apiCall } from "@/utils/http/apiCall";
import { onlySubmitData } from "@/utils/tools";

interface UseDeptForm extends UseBaseForm<DeptEntityReq> {
    getInitFormData: () => DeptEntityReq;
    handleSubmit: (isEdit: boolean, callback?: (id: string) => void) => Promise<void>;
}

export function useDeptForm(): UseDeptForm {
    /** 获取重置的表单数据 */
    const getInitFormData = (): DeptEntityReq => ({
        id: undefined,
        parentId: "",
        name: "",
        phone: null,
        email: null,
        type: "",
        level: 1,
        remark: null,
    });

    const { formRef, submitLoading, formData, resetForm } = useBaseForm<DeptEntityReq>(getInitFormData);

    /** 提交表单 */
    async function handleSubmit(isEdit: boolean, callback?: (id: string) => void): Promise<void> {
        if (!(await formRef.value?.validate())) return;
        submitLoading.value = true;

        const submitData = onlySubmitData(getInitFormData(), formData);
        const apiFn = isEdit ? deptApi.update : deptApi.create;

        apiCall(
            () => apiFn(submitData),
            (data, resp) => {
                ElMessage.success($t(resp.message));
                callback && callback(isEdit ? formData.id! : data!);
            },
            {
                onFinally: () => {
                    submitLoading.value = false;
                },
            },
        );
    }

    return {
        getInitFormData,
        formData,
        resetForm,
        formRef,
        submitLoading,
        handleSubmit,
    };
}
